﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using WCFMINERP.COM;

using WCFMINERP.InnerFactory.IView;
using WCFMINERP.InnerFactory.Presenter;
using WCFMINERP.InnerFactoryContracts.DataContracts;

using FastReport;
using System.Runtime.InteropServices;


namespace WCFMINERP.InnerFactory.Forms
{
    public partial class FrmMain :Form,IFormMain
    {
        public FrmMain()
        {
            InitializeComponent();
      
        }

        private MainPresenter _presenter;
        private void textEdit_BarCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == (int)Keys.Enter)
            {
                if (!checkEditOnlyPrint.Checked)
                {
                    if (!checkEditScanPhoto.Checked)
                    {
                        string strBarcode = textEdit_BarCode.Text.Trim();
                        int length = strBarcode.Length;
                        if (length < 10)
                        {
                            string str0 = "";
                            for (int i = 0; i < 9 - length; i++)
                            {
                                str0 += "0";
                            }
                            strBarcode = "2" + str0 + strBarcode;
                        }
                        if (!ExsitBarcode(strBarcode))
                        {
                            Properties.Settings.Default.RePrintBarcodes += strBarcode + ",";
                            Properties.Settings.Default.Save();
                        }
                        textEdit_BarCode.Text = strBarcode;
                        this.CurrBarCode = strBarcode;
                        _presenter.StartProduce();
                        textEdit_BarCode.Text = "";
                        this.CurrBarCode = "";
                    }
                    else
                    {
                        string strBarcode = textEdit_BarCode.Text.Trim();
                        int length = strBarcode.Length;
                        if (length < 10)
                        {
                            string str0 = "";
                            for (int i = 0; i < 9 - length; i++)
                            {
                                str0 += "0";
                            }
                            strBarcode = "3" + str0 + strBarcode;
                        }
                        ProduceView view = _presenter.GetViewbyBphotoBar(strBarcode);
                        strBarcode = view.ProductCode.ToString();
                        if (!ExsitBarcode(strBarcode))
                        {
                            Properties.Settings.Default.RePrintBarcodes += strBarcode + ",";
                            Properties.Settings.Default.Save();
                        }
                        textEdit_BarCode.Text = strBarcode;
                        this.CurrBarCode = strBarcode;
                        _presenter.StartProduce();
                        textEdit_BarCode.Text = "";
                        this.CurrBarCode = "";
                    }

                }

                else
                { //只打印
                    if (!checkEditScanPhoto.Checked)
                    {
                        string strBarcode = textEdit_BarCode.Text.Trim();
                        int length = strBarcode.Length;
                        if (length < 10)
                        {
                            string str0 = "";
                            for (int i = 0; i < 9 - length; i++)
                            {
                                str0 += "0";
                            }
                            strBarcode = "2" + str0 + strBarcode;
                        }
                        _presenter.PrintBarCode(strBarcode);
                    }
                    else
                    {//照片
                        string strBarcode = textEdit_BarCode.Text.Trim();
                        int length = strBarcode.Length;
                        if (length < 10)
                        {
                            string str0 = "";
                            for (int i = 0; i < 9 - length; i++)
                            {
                                str0 += "0";
                            }
                            strBarcode = "3" + str0 + strBarcode;
                        }
                        _presenter.PrintBarCodeByPhotoCode(strBarcode);
                    }
                }
                textEdit_BarCode.Text = "";
                this.CurrBarCode = "";
            }
        }

       /// <summary>
       /// 条码是否已存在
       /// </summary>
       /// <param name="EnterBarcode"></param>
       /// <returns></returns>
        private bool ExsitBarcode(string EnterBarcode)
        {
            string barcodes = Properties.Settings.Default.RePrintBarcodes;
            string[] barcodeArray = barcodes.Split(',');
            return  barcodeArray.Contains(EnterBarcode.Trim());
        }
        #region


        public string CurrBarCode
        {
            set;
            get;
        }

        public int FactoryId
        {
            set;
            get;
        }

       

        public bool IsPrintBarCode
        {
            set;
            get;
        }

        public int PrintNum
        {
            set;
            get;
        }

        public OutProcessShop_Info CurrOutShop
        {
            set;
            get;
        }
        List<string> listShop ;
        List<string> ListCtmName ;
        List<ProduceView> listView=new List<ProduceView>();
        public void DisplayList(List<ProduceView> list)
        {

            gridControlOutRecord.DataSource = list;
            gridControlOutRecord.RefreshDataSource();
            listView = list;
            listShop=new List<string>();
            listShop.Add("全部商户");
            comboBoxShop.Items.Clear();
            comboBoxShop.Items.Add("全部商户");
            ListCtmName = new List<string>();
            ListCtmName.Add("全部客户");
            comboBoxCtm.Items.Clear();
            comboBoxCtm.Items.Add("全部客户");
            labelCount.Text = list.Count.ToString();//显示记录数
            foreach (ProduceView view in list)
            {
                string shop="";
                shop = listShop.Find(delegate(string stra)
                                            {
                                                if (stra.Equals(view.ShopName))
                                                {
                                                    return true;
                                                }
                                                else
                                                {
                                                    return false;
                                                }
                                            });
                if(shop==null)
                {
                    listShop.Add(view.ShopName);
                    comboBoxShop.Items.Add(view.ShopName);
                }
                string ctmName = "";
                ctmName = ListCtmName.Find(delegate(string strb)
                                           {
                                               if(strb.Equals(view.CtmName))
                                               {
                                                   return true;
                                               }
                                               else
                                               {
                                                   return false;
                                               }
                                              
                                               
                                           });
                if(ctmName==null)
                {
                    ListCtmName.Add(view.CtmName);
                    comboBoxCtm.Items.Add(view.CtmName);
                }
            }
            textEdit_BarCode.Text = "";
            

        }
        #endregion//接口实现

        private void FrmMain_Load(object sender, EventArgs e)
        {
            try
            {
                int factoryId = Properties.Settings.Default.FactoryId;
                //if (factoryId == 0)
                //{
                //    FrmFactorySelect frmFactorySelect = new FrmFactorySelect();
                //    frmFactorySelect.List = _bll.GetAllInnerFactory();
                //    if (frmFactorySelect.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                //    {
                //        this.FactoryId =
                //            ((OutProcessShop_Info)frmFactorySelect.comboBoxFactorySelect.SelectedItem).OutShopId;
                //        if (FactoryId == 0)
                //        {


                //        }
                //        this.CurrOutShop = (OutProcessShop_Info)frmFactorySelect.comboBoxFactorySelect.SelectedItem;
                //        if (CurrOutShop == null)
                //        {

                //        }
                //        else
                //        {
                //            this.Text = CurrOutShop.OutShopName;
                //        }
                //        Properties.Settings.Default.FactoryId = FactoryId;
                //        Properties.Settings.Default.Save();

                //    }
                //    else
                //    {
                //        this.Close();
                //    }

                //}
                _presenter = new MainPresenter(this);
                if (InnerFactoryParameter.OutProcessShopInfo == null)
                {
                    InnerFactoryParameter.OutProcessShopInfo = _presenter.GetOutShopInfoById(Properties.Settings.Default.FactoryId);
                }
                this.CurrOutShop = InnerFactoryParameter.OutProcessShopInfo;
                FactoryId = CurrOutShop.OutShopId;
                this.Text = CurrOutShop.OutShopName;
                this.Cursor = Cursors.WaitCursor;
                _presenter.initForm();
                this.Cursor = Cursors.Default;
                checkEditIsBarCode.Checked = Properties.Settings.Default.IsBarCode;
                spinEditNum.EditValue = Properties.Settings.Default.intBarCode;
                //labeluser.Text = this.userName;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void gridViewRecord_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle >= 0)
            {
                string barcode = ((ProduceView)gridViewRecord.GetRow(e.FocusedRowHandle)).ProductCode.ToString();
                this.textEdit_BarCode.Text = barcode;
                
                this.CurrBarCode = barcode;
                int IntStutas2 = ((ProduceView)gridViewRecord.GetRow(e.FocusedRowHandle)).IntStutas2;
                if (IntStutas2 == (int)OutProcessRecordStatus2.Doing)
                {
                    isProdecing = true;
                }else
                {
                    isProdecing = false;
                }
            }
        }

        private bool isProdecing = false;
        private void simpleButtonPause_Click(object sender, EventArgs e)
        {

            if (isProdecing)
            {
                FrmPause frmPause = new FrmPause(InnerFactoryParameter.UserInfo.UserId, this.CurrBarCode);
                frmPause.ShowDialog();

                _presenter.initForm();
                isProdecing = false;
            }
            else
            {
                MessageBox.Show("产品不在生产中！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);


            }
        }

        private void checkEditIsBarCode_CheckStateChanged(object sender, EventArgs e)
        {
            if (checkEditIsBarCode.Checked == true)
            {
                spinEditNum.Enabled = true;
                Properties.Settings.Default.IsBarCode = true;
            }
            else
            {
                spinEditNum.Enabled = false;
                Properties.Settings.Default.IsBarCode = false;
            }
            Properties.Settings.Default.Save();
        }

        private void spinEditNum_EditValueChanged(object sender, EventArgs e)
        {
            Properties.Settings.Default.intBarCode = Convert.ToInt32(spinEditNum.EditValue);
            Properties.Settings.Default.Save();
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            Environment.Exit(0);
        }

      

        private void simpleButtonRush_Click(object sender, EventArgs e)
        {
            _presenter.initForm();//刷新
        }

        private void comboBoxShop_SelectionChangeCommitted(object sender, EventArgs e)
        {
            comboBoxCtm.Text = "";
            string shop = comboBoxShop.SelectedItem.ToString();
            if("全部商户".Equals(shop))

            {
                gridControlOutRecord.DataSource = listView;
                gridControlOutRecord.RefreshDataSource();
                return;
            }
            List<ProduceView> views = listView.Where(p => p.ShopName == shop).ToList();
            gridControlOutRecord.DataSource = views;
            gridControlOutRecord.RefreshDataSource();

        }

        private void comboBoxCtm_SelectionChangeCommitted(object sender, EventArgs e)
        {
            comboBoxCtm.Text = "";
            string ctmName = comboBoxCtm.SelectedItem.ToString();
            if ("全部客户".Equals(ctmName))
            {
                gridControlOutRecord.DataSource = listView;
                gridControlOutRecord.RefreshDataSource();
                return;

            }

            List<ProduceView> views = listView.Where(p => p.CtmName == ctmName).ToList();
            gridControlOutRecord.DataSource = views;
            gridControlOutRecord.RefreshDataSource();
        }

        private void gridViewRecord_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            //if (e.Column.Caption.Equals("开始生产时间"))
            //{
            //    if((e.CellValue.ToString().StartsWith("2000")))
            //    e.DisplayText = "";
            //}
            //if (e.Column.Caption.Equals("结束生产时间"))
            //{
            //    if ((e.CellValue.ToString().StartsWith("2000")))
            //    e.DisplayText="";
            //}
            //if (e.Column.Caption.Equals("预完成时间"))
            //{
            //    if (e.CellValue.ToString().StartsWith("2000"))
            //        e.DisplayText = "";
            //}

        }

        private void gridViewRecord_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                DateTime time=((ProduceView)gridViewRecord.GetRow(e.RowHandle)).PreCompleteDateTime;
                if (time.CompareTo(DateTime.Now) < 0)
                {
                    e.Appearance.BackColor = Color.LightPink;
                }
            }
        }

        private void simpleButtonExport_Click(object sender, EventArgs e)
        {

            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "文本文件 (*.txt)|*.txt|pdf(*.pdf)|*.pdf|电子表格(*.xls)|*.xls|html(*.html)|*.html";
            //saveFileDialog.AddExtension = true;
            saveFileDialog.FilterIndex = 3;
            saveFileDialog.RestoreDirectory = true;
            if(saveFileDialog.ShowDialog()==System.Windows.Forms.DialogResult.OK)
            {
                string fileName = saveFileDialog.FileName;
                if (saveFileDialog.OpenFile() != null)
                {
                    switch (saveFileDialog.FilterIndex)
                    {
                        case 3:
                            gridViewRecord.ExportToXls(fileName);
                            return;
                        case 4:
                            gridViewRecord.ExportToHtml(fileName);
                            return;
                        case 2:
                            gridViewRecord.ExportToPdf(fileName);
                            return;
                        case 1:
                            this.gridViewRecord.ExportToText(fileName);
                            return;
                        default:
                            break;
                    }
                }

            }

            // gridViewRecord.ExportToXls();
            
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            FrmPrint frmPrint = new FrmPrint();
            frmPrint.ShowDialog();
        }
        private string FormatProductCode()
        {

            string code = textEdit_BarCode.Text.Trim();
            if (code.Length < 10)
            {
                int c = Convert.ToInt32(code);
                code = "2" + string.Format("{0:d9}", c);
            }
            return code;
        }

        private void simpleButtonMessage_Click(object sender, EventArgs e)
        {
        
        }

        [DllImport("shell32.dll ")]
        private static extern int ShellExecute(IntPtr hwnd, StringBuilder lpszOp, StringBuilder lpszFile, StringBuilder lpszParams, StringBuilder lpszDir, int FsShowCmd);
       


        private void gridViewRecord_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
                        if (e.RowHandle >= 0&&e.Button==MouseButtons.Left)
            {
                if (e.Column.Name == "orderPicPath")
                {

                    ProduceView curPv = (ProduceView)gridViewRecord.GetRow(e.RowHandle);
                    this.CurrBarCode = curPv.ProductCode;
                    string strOrderPath = curPv.OrderPath;

                    try
                    {
                        ShellExecute(IntPtr.Zero, new StringBuilder("open"), new StringBuilder("explorer.exe"),
                                                 new StringBuilder(strOrderPath), new StringBuilder(string.Empty), 1);
                        _presenter.StartProduce();
                    }
                    catch
                    {

                    }
                }
             
            }
          
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            _presenter.PrintBarCode();
        }

        private void simpleButtonReprint_Click(object sender, EventArgs e)
        {
            Report report=new Report();
            report.Load(Application.StartupPath + "\\FactoryBarCode.frx");
            //report.PrintSettings.ShowDialog = false;
            //report.Show();
            report.Print();
        }

        private void btnReprintBarcodes_Click(object sender, EventArgs e)
        {
            string barcodes =Properties.Settings.Default.RePrintBarcodes;
            string [] arryBarcode= barcodes.Split(',');
            foreach (var item in arryBarcode)
            {
                if (item.Trim() != string.Empty)
                {
                    _presenter.PrintBarCode(item.ToString());
                }
            }
            Properties.Settings.Default.RePrintBarcodes = "";
            Properties.Settings.Default.Save();
            
        }
       
    }
   
}
